package com.sk.weichat.ui.mucfile;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.R;

import com.sk.weichat.ui.base.LazyFragment;
import com.sk.weichat.ui.mucfile.adapter.DividerAdapter;
import com.sk.weichat.ui.mucfile.adapter.EmptyAdapter;
import com.sk.weichat.ui.mucfile.adapter.MediaImageAdapter2;
import com.sk.weichat.ui.mucfile.adapter.TypeAdapter;
import com.sk.weichat.ui.mucfile.bean.FileBean;
import com.sk.weichat.util.MediaHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.sk.weichat.ui.mucfile.AddMucFileActivity2.Action_Click;

import static com.sk.weichat.ui.mucfile.bean.FileBean.DIR;
import static com.sk.weichat.ui.mucfile.bean.FileBean.IMAGE;

public class MediaImageFragment2 extends LazyFragment implements MediaHelper.OnQueryListener {
    private SmartRefreshLayout refreshLayout;
    private DelegateAdapter delegateAdapter;
    private LinkedList<DelegateAdapter.Adapter> adapterList = new LinkedList<>();
    //记录展开的项
    private Map<String, Boolean> expandMap = new HashMap<>();
    //记录选择的Item  key:文件的绝对路径 value ：是否被选中
    private Map<String, Boolean> checkedMap = new HashMap<>();
    //保存数据
    private Map<String, List<File>> cacheBeans = new HashMap<>();

    //第一次进入默认展开第一项
    private boolean once = false;

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_media_image;
    }

    @Override
    protected void loadData() {
        //扫描文件时间过长，缓存不为空，显示缓存
        List<File> files = MediaHelper.getInstance().getImageQueryCache();
        if (files != null) {
            onDataSuccess(files);
        } else {
            refreshLayout.autoRefresh();
        }
    }

    @Override
    protected void initView(View view) {
        refreshLayout = view.findViewById(R.id.refresh_layout);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                realLoadData();
            }
        });

        VirtualLayoutManager layoutManager = new VirtualLayoutManager(getActivity());

        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        viewPool.setMaxRecycledViews(0, 20);
        viewPool.setMaxRecycledViews(1, 20);
        viewPool.setMaxRecycledViews(2, 20);

        RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setRecycledViewPool(viewPool);

        delegateAdapter = new DelegateAdapter(layoutManager, false);
        recyclerView.setAdapter(delegateAdapter);

    }


    private void realLoadData() {
        //查询
        MediaHelper.getInstance().getMediaImages(getActivity().getContentResolver(), this);
    }

    private void onDataSuccess(List<File> files) {
        Observable.create(new ObservableOnSubscribe<Object>() {

            @Override
            public void subscribe(ObservableEmitter<Object> emitter) throws Exception {
                //耗时操作
                try {
                    adapterList.clear();
                    cacheBeans.clear();
                    if (files.size() > 0) {
                        fillData(files);
                    } else {
                        adapterList.add(new EmptyAdapter(mContext));
                    }
                } catch (Exception e) {
                    emitter.onError(e);
                }
                emitter.onNext(new Object());
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {

                    @Override
                    public void accept(Object o) throws Exception {
                        delegateAdapter.clear();
                        delegateAdapter.addAdapters(adapterList);
                        delegateAdapter.notifyDataSetChanged();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        Log.e("lzs", "throwable:" + throwable.getMessage());
                    }
                });
    }
    //


    private void fillData(List<File> files) {
        Map<String, List<File>> fileMap = new HashMap<>();
        for (int i = 0; i < files.size(); i++) {
            File file = files.get(i);
            //按目录分类
            String parentPath = file.getParent();
            if (fileMap.get(parentPath) == null) {
                List<File> files1 = new ArrayList<>();
                files1.add(file);
                fileMap.put(parentPath, files1);
            } else {
                fileMap.get(parentPath).add(file);
            }
        }
        Iterator<Map.Entry<String, List<File>>> itr = fileMap.entrySet().iterator();
        int index = 0;

        while (itr.hasNext()) {
            //加入标题项
            Map.Entry<String, List<File>> entry = itr.next();
            String dir = entry.getKey();
            TypeAdapter typeAdapter = getTypeAdapter(dir);

            adapterList.add(typeAdapter);
            List<File> fileList = entry.getValue();
            List<FileBean> list = new ArrayList<>();
            MediaImageAdapter2 imageAdapter2 = new MediaImageAdapter2(mContext, list);
            imageAdapter2.setOnImageClickListener(new MediaImageAdapter2.OnImageClickListener() {
                @Override
                public void onClick(FileBean fileBean) {
                    if (AddMucFileActivity2.isAllowToSelect() || fileBean.isChecked()) {
                        fileBean.setChecked(!fileBean.isChecked());
                        checkedMap.put(fileBean.getFile().getAbsolutePath(), fileBean.isChecked());
                        imageAdapter2.notifyItemChanged(imageAdapter2.getData().indexOf(fileBean));
                        //发送广播
                        Intent intent = new Intent();
                        intent.setAction(Action_Click);
                        intent.putExtra(FileBean.FileBean_Key, fileBean);
                        LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
                    } else {
                        Toast.makeText(mContext, mContext.getString(R.string.select_file_count_place_holder, 9), Toast.LENGTH_SHORT).show();
                    }
                }
            });
            adapterList.add(imageAdapter2);
            adapterList.add(new DividerAdapter(mContext));
            cacheBeans.put(dir, fileList);
            if (index == 0 && !once) {
                typeAdapter.getData().get(0).setExpand(true);
                once = true;
                expandMap.put(dir, true);
                list.addAll(fileList2FileBeanList(dir, fileList));
            } else if (expandMap.get(dir) != null && expandMap.get(dir)) {
                list.addAll(fileList2FileBeanList(dir, fileList));
            }
        }
    }

    private TypeAdapter getTypeAdapter(String type) {
        FileBean fileBean = new FileBean();
        fileBean.setType(DIR);
        fileBean.setTypeName(type);
        List<FileBean> fileBeans = new ArrayList<>();
        fileBeans.add(fileBean);
        TypeAdapter adapter = new TypeAdapter(mContext, fileBeans);
        adapter.getData().get(0).setExpand(expandMap.get(type) == null ? false : expandMap.get(type));
        //点击展开或者折叠
        adapter.setOnTypeClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FileBean data = adapter.getData().get(0);
                if (data.isExpand()) {
                    expandMap.put(data.getTypeName(), false);
                    //折叠
                    data.setExpand(false);
                    //清空子分类的数据
                    int index = adapterList.indexOf(adapter);
                    MediaImageAdapter2 imageAdapter2 = (MediaImageAdapter2) adapterList.get(index + 1);
                    List<FileBean> data2 = imageAdapter2.getData();
                    if (data2 != null) {
                        data2.clear();
                        imageAdapter2.notifyItemRangeRemoved(0, data2.size());
                    }
                } else {
                    expandMap.put(data.getTypeName(), true);
                    //展开
                    data.setExpand(true);
                    //增加子分类数据
                    int index = adapterList.indexOf(adapter);
                    MediaImageAdapter2 imageAdapter2 = (MediaImageAdapter2) adapterList.get(index + 1);
                    List<FileBean> data2 = imageAdapter2.getData();
                    if (data2 != null) {
                        data2.clear();
                        data2.addAll(fileList2FileBeanList(data.getTypeName(), cacheBeans.get(data.getTypeName())));
                        imageAdapter2.notifyItemRangeInserted(0, data2.size());
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });
        return adapter;
    }

    private List<FileBean> fileList2FileBeanList(String type, List<File> fileList) {
        List<FileBean> fileBeanList = new ArrayList<>();
        for (int i = 0; i < fileList.size(); i++) {
            FileBean bean = new FileBean();
            if (checkedMap.get(fileList.get(i).getAbsolutePath()) != null && checkedMap.get(fileList.get(i).getAbsolutePath())) {
                bean.setChecked(true);
            }
            bean.setType(IMAGE);
            bean.setFile(fileList.get(i));
            fileBeanList.add(bean);
        }
        return fileBeanList;
    }


    @Override
    public void onSuccess(List<File> files) {
        refreshLayout.finishRefresh();
        onDataSuccess(files);
    }

    @Override
    public void onFailed(String msg) {
        refreshLayout.finishRefresh();
    }
}
